<?php

namespace app\common\model;

use app\common\model\CouponReceive;

class Cart extends Base
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'ddt_cart';
    // 主键ID
    protected $pk = 'cart_id';

//    function get_cart_list($userinfo,$page=1,$limit=5,$type = 1,$shop_id = ''){
//        $cwhere = [
//            ['cart.user_id','=',$userinfo['user_id']],
//            ['cart.type','=',$type],
//        ];
//        $type == 2?$cwhere[] = ['cart.shop_id','=',$shop_id]:'';
//        $cartfield = 'cart.*';
//        $shopfield = 'shops.shop_name,shops.imagesurl,shops.approved as sa,shops.state as ss';
//        $productfield = 'products.product_name,products.price,products.mprice,products.sprice,products.imageurl,products.approved as pa,products.state as ps,products.is_del as pd';
//        $stockfield = 'stock.p_s_name,stock.stock,stock.is_del as sd';
//        $field = $cartfield.','.$shopfield.','.$productfield.','.$stockfield;
//        $data = $this
//            ->alias('cart')
//            ->leftJoin("ddt_shops shops","cart.shop_id = shops.shop_id")
//            ->leftJoin('ddt_products products',"cart.product_id = products.product_id")
//            ->leftJoin('ddt_products_stock stock',"cart.p_s_id = stock.p_s_id")
//            ->where($cwhere)
//            ->order('cart.add_time desc')
////            ->group('cart.shop_id')
//            ->field($field)
////            ->page($page,$limit)
////            ->select();
//            ->paginate($limit);
//        if(!$data){
//            return [];
//        }
//        $result = [
//            "total"=> $data->total(),
//            "per_page"=> $data->listRows(),
//            "current_page"=> $data->currentPage(),
//            "last_page"=> $data->lastPage(),
//        ];
//        $data = $data->toArray();
////        var_dump($data);die;
//        $carts = [];
//        $number = 0;
//        $utype = $userinfo['utype'] == 2 ?'mprice':'sprice';
//        $shopids = array_unique(array_column($data['data'],'shop_id'));
//		foreach($shopids as $key => $value){
////            var_dump($value);
//			$carts[$key]["shop"] = null;
//			$i = 0;
//			foreach($data['data'] as $k => $v){
//				if($value == $v['shop_id']){
////                    var_dump($k);
//					$v['is_validity'] = true;
//					$carts[$key]["shop"]["shop_id"] = $v['shop_id'];
//					$carts[$key]["shop"]["shop_name"] = $v['shop_name'];
//					$carts[$key]["shop"]["imagesurl"] = $v['imagesurl'];
//					if($value == 0){
//						if($v['ps'] != 1 || $v['pa'] !=2 || $v['pd'] != 1 || $v['sd'] != 1 || $v['quantity'] > $v['stock']){
//							$v['is_validity'] = false;
//						}
////                        var_dump($v);die;
//					} else {
//						if($v['sa'] != 1 || $v['ss'] != 1 || $v['ps'] != 1 || $v['pa'] !=2 || $v['pd'] != 1 || $v['sd'] != 1 || $v['quantity'] > $v['stock']){
//							$v['is_validity'] = false;
//						}
//					}
//					$carts[$key]["products"][$i] = $v;
//					$carts[$key]["products"][$i]['sale_price'] = $v[$utype];
//					$number += $v['quantity'];
//					$i += 1;
//				}
//			}
//		}
//		$carts = array_values($carts);
//        $result["data"] = $carts;
//        $result["number"] = $number;
////        var_dump($carts);die;
////        var_dump($shopids);
////        var_dump($data);die;
//
//        return $result;
//    }
    function get_cart_list($userinfo,$type = 1,$shop_id = ''){
        $cwhere = [
            ['cart.user_id','=',$userinfo['user_id']],
            ['cart.type','=',$type],
        ];
        $type == 2?$cwhere[] = ['cart.shop_id','=',$shop_id]:'';
        $cartfield = 'cart.*';
//        $shopfield = 'shops.shop_name,shops.imagesurl,shops.approved as sa,shops.state as ss';
        $productfield = 'products.product_name,products.price,products.mprice,products.sprice,products.imageurl,products.approved as pa,products.state as ps,products.is_del as pd,products.describe';
        $field = $cartfield.','.$productfield;
        $data = $this
            ->alias('cart')
            ->leftJoin('ddt_products products',"cart.product_id = products.product_id")
            ->where($cwhere)
            ->order('cart.add_time desc')
//            ->group('cart.shop_id')
            ->field($field)
//            ->page($page,$limit)
            ->select();
//            ->paginate($limit);
        if(!$data){
            return [];
        }
        $data = $data->toArray();
//        var_dump($data);die;
        $carts = [];
        $number = 0;
        $amount = 0.00;
        $utype = $userinfo['utype'] == 2 ?'mprice':'sprice';
			$i = 0;
        foreach($data as $k => $v){
            $v['is_validity'] = true;
            if($v['ps'] != 1 || $v['pa'] !=2 || $v['pd'] != 1){
                $v['is_validity'] = false;
            }
            $carts[$i] = $v;
            $carts[$i]['sale_price'] = $v[$utype];
            $amount = calculate([calculate([$v[$utype],$v['quantity']],'*',2),$amount]);
            $number += $v['quantity'];
            $i += 1;
        }
		$carts = array_values($carts);
        $result["cart"] = $carts;
        $result["number"] = $number;
        $result["amount"] = $amount;
//        var_dump($carts);die;
//        var_dump($shopids);
//        var_dump($data);die;

        return $result;
    }

    //新增、编辑(后台操作)
    function edit($params, $id=0){
        if($id>0){
            // 更新条件
            $where = ['cart_id' => $id];
            $params['update_time'] = time();
            $rs = $this->allowField(true)->save($params, $where);
        }else{
            // 更新数据
            $params['add_time'] = time();
            $params['update_time'] = time();
            $this->save($params);
            $rs = $this->cart_id;
        }
//        var_dump($rs);die;
        if ($rs === false) {
            $this->setError(-1, '操作失败');
            return false;
        }
        $id > 0? $rs = $id:'';
        return $rs;
    }

//    //用户新增编辑购物车
//    function editcart($user_id,$product_id,$p_s_id, $quantity = 1,$type = 1){
//        $productModel = new Products();
//        $product = $productModel->where('product_id','=',$product_id)->find();
//        if(empty($product)){
//            $this->setError(-1,'该商品不存在');
//            return false;
//        }
//        $productdata = $product->toArray();
//        if($productdata['state'] != 1 || $productdata['approved'] !=2 || $productdata['is_del'] != 1){
//            $this->setError(-1,'该商品已下架');
//            return false;
//        }
////        var_dump($productdata);
//        if($productdata['shop_id'] != 0){
//            $shopModel = new Shops();
//            $shop = $shopModel->where('shop_id','=',$productdata['shop_id'])->find();
//            if(empty($shop)){
//                $this->setError(-1,'该商铺不存在');
//                return false;
//            }
//            $shopdata = $shop->toArray();
//            if($shopdata['state'] != 1 || $shopdata['approved'] != 1){
//                $this->setError(-1,'该商铺已暂停营业');
//                return false;
//            }
//        }
//        $stockModel = new ProductStock();
//        $stock = $stockModel->where('product_id','=',$product_id)->where('p_s_id','=',$p_s_id)->find();
//        if(empty($stock)){
//            $this->setError(-1,'不存在该商品库存');
//            return false;
//        }
//        $stockdata = $stock->toArray();
//        if($stockdata['is_del'] != 1){
//            $this->setError(-1,'商品库存不存在');
//            return false;
//        }
//        if($stockdata['stock'] < $quantity){
//            $this->setError(-1,'该规格商品库存不足');
//            return false;
//        }
//        $cwhere = [
//            ['user_id','=',$user_id],
//            ['product_id','=',$product_id],
//            ['p_s_id','=',$p_s_id],
//        ];
//        $cart = $this
//            ->where($cwhere)
//            ->field('*')
//            ->find();
//        $params = [
//            "user_id" => $user_id,
//            "shop_id" => $productdata['shop_id'],
//            "product_id" => $productdata['product_id'],
//            "p_s_id" => $stockdata['p_s_id'],
//            "quantity" => $quantity,
//            "type" => $type,
//        ];
//        if(empty($cart)){
//            $rs = $this->edit($params);
////            $data = [
////                "params" => $params,
////                "cart_id" => 0,
////            ];
//        } else {
//            $rs = $this->edit($params,$cart->toArray()['cart_id']);
////            $data = [
////                "params" => $params,
////                "cart_id" => $cart->toArray()['cart_id'],
////            ];
//        }
//        if ($rs === false) {
//            return false;
//        }
//        return $rs;
//    }

    //用户新增编辑购物车
    function editcart($user_id,$product_id, $quantity = 1,$type = 1){
        $productModel = new Products();
        $product = $productModel->where('product_id','=',$product_id)->find();
        if(empty($product)){
            $this->setError(-1,'该商品不存在');
            return false;
        }
        $productdata = $product->toArray();
        if($productdata['state'] != 1 || $productdata['approved'] !=2 || $productdata['is_del'] != 1){
            $this->setError(-1,'该商品已下架');
            return false;
        }
//        var_dump($productdata);
        if($productdata['shop_id'] != 0){
            $shopModel = new Shops();
            $shop = $shopModel->where('shop_id','=',$productdata['shop_id'])->find();
            if(empty($shop)){
                $this->setError(-1,'该商铺不存在');
                return false;
            }
            $shopdata = $shop->toArray();
            if($shopdata['state'] != 1 || $shopdata['approved'] != 1){
                $this->setError(-1,'该商铺已暂停营业');
                return false;
            }
        }
        $cwhere = [
            ['user_id','=',$user_id],
            ['product_id','=',$product_id],
        ];
        $cart = $this
            ->where($cwhere)
            ->field('*')
            ->find();
        $params = [
            "user_id" => $user_id,
            "shop_id" => $productdata['shop_id'],
            "product_id" => $productdata['product_id'],
            "quantity" => $quantity,
            "type" => $type,
        ];
        if(empty($cart)){
            $rs = $this->edit($params);
//            $data = [
//                "params" => $params,
//                "cart_id" => 0,
//            ];
        } else {
            $rs = $this->edit($params,$cart->toArray()['cart_id']);
//            $data = [
//                "params" => $params,
//                "cart_id" => $cart->toArray()['cart_id'],
//            ];
        }
        if ($rs === false) {
            return false;
        }
        return $rs;
    }

//    删除购物车
    function delcart($userid,$ids){
        $rs = $this
            ->where('user_id','=',$userid)
            ->where('cart_id','in',$ids)
            ->delete();
        if(!$rs){
            $this->setError(-1,'删除失败');
            return false;
        }
        return true;
    }

//	function Settlement($user,$ids,$receive_id,$type = 1){
//		//查出购物车ID里面的商铺，整合起来；
//		//因为里面会有商铺ID为0的数据，所以不能连表查询商铺信息
//		$shop_ids = $this
//			->field('shop_id')
//			->where('user_id','=',$user['user_id'])
//            ->where('type','=',$type)
//			->where('cart_id','in',$ids)
//			->group('shop_id')
//			->column('shop_id');
////        var_dump(count($shop_ids));die;
//		if(count($shop_ids)>1){
//		    $this->setError(-1,'请选择相同商家的商品下单');
//		    return false;
//        }
//		//查询商铺信息
//		$shopModel = new Shops();
//		$shoplist = $shopModel
//			->field('shop_id,shop_name,imagesurl')
//			->where('approved','=',1)
//			->where('state','=',1)
//			->where('shop_id','in',$shop_ids)
//			->select()->toArray();
//		//校验商铺数据是否正常
//		if($shoplist){
//			$shoplist_column = array_column($shoplist,null,'shop_id');
//		}
//        $newshoplist = [];
//		foreach ($shop_ids as $value){
////			if($value == 0){
////				$newshoplist[$value] = ['shop_id' => 0,'shop_name' => '总部'];
////			}
//			if(!empty($shoplist_column[$value])){
//				$newshoplist[$value] = $shoplist_column[$value];
//			}
//		}
//		if(count($shop_ids) != count($newshoplist)){
//            $this->setError(-1,'商铺数量前后不一致');
//			return false;
//		}
//
//		//查询商品信息
//		$products = $this
//			->alias('cart')
//			->field('cart.cart_id,cart.quantity,cart.p_s_id,cart.product_id,p.shop_id,p.product_name,p.price,p.mprice,p.sprice,p.express_fee,p.imageurl,p.growth_coin,p.department_id,s.p_s_name')
//			->where([
//				['cart.user_id','=',$user['user_id']],
//				['p.state','=',1],
//				['p.approved','=',2],
//				['cart.type','=',$type],
//				['cart.cart_id','in',$ids],
//			])
//			->where("s.stock > cart.quantity")
//			->leftJoin('ddt_products p',"cart.product_id = p.product_id")
//			->leftJoin('ddt_products_stock s',"cart.p_s_id = s.p_s_id")
//			->select()->toArray();
////		print_r($products);die;
//		if(!$products){
//            $this->setError(-1,'该商品已下架');
//			return false;
//		}
////		echo $this->getLastSql();die;
//
//
//		//商品总价
//		$allproducts_amount = 0.00;
//		//订单使用优惠券减少的金额
//		$allcoupon_amount = 0.00;
//		//总运费
//		$allexpress_fee = 0.00;
//		//订单总价 = 商品总价-优惠券金额(不包含运费)
//		$allorder_amount = 0.00;
//		//商品总件数
//        $case_number = 0;
//		//用户可获得的总积分
//        $all_growth_coin = 0;
//        //优惠卷使用情况
//        $is_coupon = true;
//
//		// 会员折扣
//		$utype = $user['utype'] == 2 ?'mprice':'sprice';
//		foreach ($products as $key => $value){
//		    $value['sale_price'] = $value[$utype];
//			$newshoplist[$value['shop_id']]['product'][] = $value;
//			$products[$key]['sale_price'] = $value[$utype];
//
//			//计算商品总价
//			$price = calculate([
//				$value[$utype],$value['quantity']
//			],'*');
//			$allproducts_amount =calculate([$price,$allproducts_amount]);
//
//			//计算总运费
//			$allexpress_fee =calculate([$value['express_fee'],$allexpress_fee]);
//
//			//计算商品总件数
//			$case_number =calculate([$value['quantity'],$case_number],'+',0);
//
//			//计算用户可获得的总积分
//            $all_growth_coin = calculate([
//                calculate([$value['quantity'],$value['growth_coin']],'*',0),
//                $all_growth_coin
//            ],'+',0);
//		}
//
//		//计算订单使用优惠券减少的金额
//		if($receive_id){
//			$CouponReceiveModel = new CouponReceive();
//			$Coupon = $CouponReceiveModel->where(['receive_id'=>$receive_id,'user_id'=>$user['user_id'],'is_use'=>1])->find();
//			if(empty($Coupon)){
//                $this->setError(-1,'用户不存在的消费券');
//			    return false;
//            }
//			$Coupon = $Coupon->toArray();
//			if($Coupon && $allproducts_amount >= $Coupon['fullmoney']){
//				//计算订单使用优惠券减少的金额
//				$allcoupon_amount = $Coupon['discount'];
//				//计算订单总价
//				$allorder_amount=calculate([$allproducts_amount,$Coupon['discount']],'-');
//			} else {
//                //计算订单使用优惠券减少的金额
//                $allcoupon_amount = 0;
//                //计算订单总价
//                $allorder_amount=$allproducts_amount;
//                $is_coupon = false;
////                $this->setError(-1,'未达消费券使用条件');
////                return false;
//            }
//		}else{
//		    $is_coupon = false;
//            $allorder_amount = $allproducts_amount;
//        }
//
//		//计算实付金额;实付金额： 订单总价+运费
//		$allpay_amount = calculate([$allorder_amount,$allexpress_fee]);
//		return [
//			'list' => $newshoplist,
//            'products' => $products,
//			'price' => [
//			    'totality' => $case_number,
//				'products_amount' => $allproducts_amount,
//				'coupon_amount' => $allcoupon_amount,
//				'express_fee' => $allexpress_fee,
//				'order_amount' => $allorder_amount,
//                'pay_amount' => $allpay_amount,
//                'all_growth_coin' => $all_growth_coin,
//			],
//            'is_coupon' => $is_coupon,
//		];
//	}

	function Settlement($user,$ids,$receive_id,$type = 1){
		//查询商品信息
		$products = $this
			->alias('cart')
			->field('cart.cart_id,cart.quantity,cart.product_id,p.shop_id,p.product_name,p.price,p.mprice,p.sprice,p.describe,p.express_fee,p.imageurl,p.growth_coin,p.department_id')
			->where([
				['cart.user_id','=',$user['user_id']],
				['p.state','=',1],
				['p.approved','=',2],
				['cart.type','=',$type],
				['cart.cart_id','in',$ids],
			])
			->leftJoin('ddt_products p',"cart.product_id = p.product_id")
			->select()->toArray();
//		print_r($products);die;
		if(!$products){
            $this->setError(-1,'该商品已下架');
			return false;
		}
//		echo $this->getLastSql();die;


		//商品总价
		$allproducts_amount = 0.00;
		//订单使用优惠券减少的金额
		$allcoupon_amount = 0.00;
		//总运费
		$allexpress_fee = 0.00;
		//订单总价 = 商品总价-优惠券金额(不包含运费)
		$allorder_amount = 0.00;
		//商品总件数
        $case_number = 0;
		//用户可获得的总积分
        $all_growth_coin = 0;
        //优惠卷使用情况
        $is_coupon = true;

		// 会员折扣
		$utype = $user['utype'] == 2 ?'mprice':'sprice';
		foreach ($products as $key => $value){
		    $value['sale_price'] = $value[$utype];
//			$newshoplist[$value['shop_id']]['product'][] = $value;
			$products[$key]['sale_price'] = $value[$utype];

			//计算商品总价
			$price = calculate([
				$value[$utype],$value['quantity']
			],'*');
			$allproducts_amount =calculate([$price,$allproducts_amount]);

			//计算总运费
			$allexpress_fee =calculate([$value['express_fee'],$allexpress_fee]);

			//计算商品总件数
			$case_number =calculate([$value['quantity'],$case_number],'+',0);

			//计算用户可获得的总积分
            $all_growth_coin = calculate([
                calculate([$value['quantity'],$value['growth_coin']],'*',0),
                $all_growth_coin
            ],'+',0);
		}

		//计算订单使用优惠券减少的金额
		if($receive_id){
			$CouponReceiveModel = new CouponReceive();
			$Coupon = $CouponReceiveModel->where(['receive_id'=>$receive_id,'user_id'=>$user['user_id'],'is_use'=>1])->find();
			if(empty($Coupon)){
                $this->setError(-1,'用户不存在的消费券');
			    return false;
            }
			$Coupon = $Coupon->toArray();
			if($Coupon && $allproducts_amount >= $Coupon['fullmoney']){
				//计算订单使用优惠券减少的金额
				$allcoupon_amount = $Coupon['discount'];
				//计算订单总价
				$allorder_amount=calculate([$allproducts_amount,$Coupon['discount']],'-');
			} else {
                //计算订单使用优惠券减少的金额
                $allcoupon_amount = 0;
                //计算订单总价
                $allorder_amount=$allproducts_amount;
                $is_coupon = false;
//                $this->setError(-1,'未达消费券使用条件');
//                return false;
            }
		}else{
		    $is_coupon = false;
            $allorder_amount = $allproducts_amount;
        }

		//计算实付金额;实付金额： 订单总价+运费
		$allpay_amount = calculate([$allorder_amount,$allexpress_fee]);
		return [
//			'list' => $newshoplist,
            'products' => $products,
			'price' => [
			    'totality' => $case_number,
				'products_amount' => $allproducts_amount,
				'coupon_amount' => $allcoupon_amount,
				'express_fee' => $allexpress_fee,
				'order_amount' => $allorder_amount,
                'pay_amount' => $allpay_amount,
                'all_growth_coin' => $all_growth_coin,
			],
            'is_coupon' => $is_coupon,
		];
	}

}